//由于双端队列同时遵守了先进先出和后进先出原则，可以说它是把队列和栈相结合的一种数据结构。// 队列遵循先进先出原则fifo
class Deque {
  constructor() {
    this.count = 0; // {1} 
    this.lowestCount = 0; // {2} 
    this.items = {}; // {3} 
  }
  addFront(ele) {
    if (this.isEmpty()) {
      this.addBack(ele)
    } else if (this.lowestCount > 0) {
      this.lowestCount--
      this.items[this.lowestCount] = ele
    } else {
      for (let i = this.count; i > 0; i--) {
        this.items[i] = this.items[i - 1]
      }
      this.count++
      this.lowestCount = 0
      this.items[this.lowestCount] = ele
    }

  }
  addBack(ele) {
    this.items[this.count] = ele;
    this.count++;
  }
  removeFront() {
    if (this.isEmpty()) {
      return undefined
    }
    let result = this.items[this.lowestCount];
    delete this.items[this.lowestCount];
    this.lowestCount++
    return result
  }
  removeBack() {
    if (this.isEmpty()) {
      return undefined
    }
    this.count--
    let result = this.items[this.count];
    delete this.items[this.count]
    return result

  }
  peekFront() {
    if (this.isEmpty()) {
      return undefined
    }
    return this.items[this.lowestCount]
  }
  peekBack() {
    if (this.isEmpty()) {
      return undefined
    }
    return this.items[this.count - 1]
  }
  isEmpty() {
    return this.count - this.lowestCount === 0
  }
  size() {
    return this.count - this.lowestCount
  }
  clear() {
    this.count = 0;
    this.lowestCount = 0
    this.items = {}
  }
  toString() {
    if (this.isEmpty()) {
      return ''
    }
    let objectStr = this.items[this.lowestCount];
    for (let i = this.lowestCount + 1; i < this.count; i++) {
      objectStr = `${objectStr},${this.items[i]}`
    }
    return objectStr
  }
}

let queue = new Deque()
queue.addBack('a')
queue.addBack('b')
queue.addFront('c')
console.log(queue.toString())
console.log(queue.peekBack())
console.log(queue.peekFront())
queue.removeBack()
queue.removeFront()
console.log(queue.toString())